﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using System.Data;
using System.Text.RegularExpressions;
using Lib.Common;
using CustomUIControls;
using System.IO;

namespace Lib.CommonForm
{
    public partial class FormBase : DockContent
    {
        #region "Process Hot Key"
        internal bool HandleEsc;
        internal bool HandleLookup;
        private Dictionary<Keys, object> m_lstHotKey = new Dictionary<Keys, object>();
        private void HotKey_Init(object ctlInit)
        {
            if (ctlInit is ToolStrip)
            {
                foreach (ToolStripItem ctlChild in ((ToolStrip)ctlInit).Items)
                {
                    if (ctlChild is ToolStripButton)
                    {
                        HotKey_Init(ctlChild);
                    }
                }
            }
            else if (ctlInit is Panel)
            {
                foreach (Control ctlChild in ((Panel)ctlInit).Controls)
                {
                    if (ctlChild is Button)
                    {
                        HotKey_Init(ctlChild);
                    }
                }
            }
            else
            {

                if (ctlInit is ToolStripItem)
                {

                    if (!((ctlInit as ToolStripItem).Text.Contains("(") && (ctlInit as ToolStripItem).Text.Contains(")")))
                    {
                        //Assign system hot key init 
                        string sKeyItem = "HK_" + (ctlInit as ToolStripItem).Name.Substring(3).Split(new string[] { "_" }, StringSplitOptions.None)[0];
                        if ((FormGlobals.HotKeyData != null) && FormGlobals.HotKeyData.HasItem(sKeyItem))
                        {
                            ((ToolStripItem)ctlInit).Text += " (" + FormGlobals.HotKeyData.Item(sKeyItem) + ")";
                        }
                    }
                    string sText = ((ToolStripItem)ctlInit).Text;
                    sText = Regex.Replace(sText, ".*\\s\\((.*)\\)", "$1");
                    if (sText != ((ToolStripItem)ctlInit).Text)
                    {
                        Keys key = FormGlobals.Keys_Parse(sText);
                        if (key > 0)
                            m_lstHotKey.Add(key, ctlInit);
                    }
                }
                else
                {
                    if (!((ctlInit as Control).Text.Contains("(") && (ctlInit as Control).Text.Contains(")")))
                    {
                        //Assign system hot key init 
                        string sKeyItem = "HK_" + (ctlInit as Control).Name.Substring(3).Split(new string[] { "_" }, StringSplitOptions.None)[0];
                        if ((FormGlobals.HotKeyData != null) && FormGlobals.HotKeyData.HasItem(sKeyItem))
                        {
                            ((Control)ctlInit).Text += " (" + FormGlobals.HotKeyData.Item(sKeyItem) + ")";
                        }
                    }
                    string sText = ((Control)ctlInit).Text;
                    sText = Regex.Replace(sText, ".*\\s\\((.*)\\)", "$1");
                    if (sText != ((Control)ctlInit).Text)
                    {
                        Keys key = FormGlobals.Keys_Parse(sText);
                        if (key > 0)
                            m_lstHotKey.Add(key, ctlInit);
                    }
                }
            }
        }
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            //Key lookup process
            if (keyData == FormGlobals.CS_LOOKUP_KEY)
            {
                //Textbox lookup process
                //If TypeOf Me.ActiveControl.Tag Is FormControlExt _
                //AndAlso DirectCast(Me.ActiveControl.Tag, FormControlExt).Lookup _
                //Then
                if (HandleLookup)
                {
                    return true;
                }
            }
            //Shortcut process
            if (m_lstHotKey.ContainsKey(keyData))
            {
                if (m_lstHotKey[keyData] is ToolStrip)
                {
                    foreach (ToolStripItem ctlChild in ((ToolStrip)m_lstHotKey[keyData]).Items)
                    {
                        if (ctlChild is ToolStripButton)
                        {
                            if (((ToolStripButton)m_lstHotKey[keyData]).Enabled)
                            {
                                ((ToolStripButton)m_lstHotKey[keyData]).PerformClick();
                                return true;
                            }
                        }
                    }
                }
                else
                {
                    //Shortcut process
                    if (((Button)m_lstHotKey[keyData]).Enabled)
                    {
                        ((Button)m_lstHotKey[keyData]).PerformClick();
                        return true;
                    }
                }
            }

            //Esc process
            if (keyData == Keys.Escape && this.MdiParent == null && !HandleEsc && this.Name != "frmMain")
            {
                this.Close();
                return true;
            }
            //Allow update only in debug mode
#if (Debug)
	if (keyData == Keys.Shift + Keys.F6) {
		if (Message_Confirm("Update all button command data")) {
			//Update command button
			Control pnlCommand = Find_Control(this, "pnlCommand");
			if ((pnlCommand != null)) {
				Button_BuildAll(pnlCommand);
			}
		}
	}
#endif
            return base.ProcessCmdKey(ref msg, keyData);
        }
        #endregion

        #region "Properies"


        public bool _IsLoading = true;
        public bool IsLoading
        {
            get { return _IsLoading; }
            set { _IsLoading = value; }
        }

        private FormBase _FormRecall = null;
        public FormBase FormRecall
        {
            get { return _FormRecall; }
        }

        private List<string> m_lstButtonPermission;
        protected bool ButtonPermission
        {
            get { return true; }
        }

        protected string UserName
        {
            get { return FormGlobals.CS_USER_NAME; }
        }

        protected long UserId
        {
            get { return FormGlobals.CS_USER_ID; }
        }

        protected string[] UserRoles
        {
            get { return FormGlobals.CS_USER_ROLES_CODE.Split(new char[] { ',' }); }
        }

        private string _FormId = Guid.NewGuid().ToString();
        internal string FormId
        {
            get { return _FormId; }
        }

        private string _MenuName;
        public string MenuName
        {
            get { return _MenuName; }
            set { _MenuName = value; }
        }

        private object _InitValue;
        public object InitValue
        {
            get { return _InitValue; }
            set { _InitValue = value; }
        }

        private object _InputValue;
        public object InputValue
        {
            get { return _InputValue; }
            set { _InputValue = value; }
        }

        #endregion

        #region "Private function"

        private Button btnExit;
        private bool m_initDialog;

        public Color _toolStripBackColor = Color.FromArgb(191, 219, 255);

        //public Color _toolStripBackColor = SystemColors.Control;

        //Màu nền của Office 2007
        //public Color _backgroundColor = Color.FromArgb(227, 239, 255);

        //Màu nền của IAS
        // public Color _backgroundColor = Color.FromArgb(191, 219, 255);

        public Color _backgroundColor = SystemColors.Control;

        //Màu sau là màu cũ của dự án IBMS
        //public Color _backgroundColor = Color.FromArgb(215, 227, 242);

        public tbl_RoleRight_Info _listRole;

        public DialogResult _dlgResult;

        public int _pageSize = 25;
        public int _currentPage = 0;
        public int _itemCount = 0;
        public int _totalPage = 0;
        public string _orderBy = "";
        public string _orderDirection = "";
        public string _keyWord = "";
        public bool _isSelect = false;
        public string _userName = "";
        public int _branchId = 0;
        public string _branchCode = "";
        public int _departmentId = 0;
        public string _departmentCode = "";
        public Dictionary<String, String> _dicExchaneValue;
        public Dictionary<String, String> _dicRootValue;
        public bool _saving = true;//Khi lưu sẽ chặn các sự kiên Validated, Leave, để tránh focus lần 2 vào control khi checkvalid

        private ToolStripButton btnExitToolbar;



        public void Init_Form()
        {
            //Init form control style
            FormGlobals.Control_SetFlat(this);
            FormGlobals.Control_SetStyle(this);

            //Init track input value
            //Init_TrackInput();

            //Init command panel
            Control pnlCommand = (Control)FormGlobals.Find_Control<Control>(this, "pnlCommand");
            if ((pnlCommand != null))
                FormGlobals.Panel_InitCommand(pnlCommand);

            //Init command panel
            Button_InitCommand(this);

            //Init toolbar
            Toolbar_InitCommand(this);


            //Init input custom valid
            Control grbInput = (Control)FormGlobals.Find_Control(this, "grbInput");
            if ((grbInput != null))
            {
                Control_HandlerValid(grbInput);
                //chua chuyen sang
            }
            //
            if (m_initDialog)
            {
                //this.Padding = new Padding(2, 2, 2, 2);
                if ((btnExit != null))
                {
                    btnExit.DialogResult = DialogResult.Cancel;
                    btnExit.CausesValidation = false;
                }
            }
            else
            {
                //this.Padding = new Padding(2, 2, 2, 2);
                if ((btnExit != null))
                    btnExit.DialogResult = DialogResult.None;
            }

            //call form control init
            Init_Control();
            //init tab order
            Init_TabOrder();
            //init tab focus

            //finish loading
            _IsLoading = false;

            /*
            this.Text += " ";

            //Set iCon for all form
            //System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormBase));
            //this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));

            //FormGlobals.Control_SetStyle(this);

            //Init TabOrder
            SetTabOrder(this);

            //
            //Init BackColor and ForeColor
            Control_Color(this);

            //
            

            this.KeyPreview = true;
            this.KeyPress += new KeyPressEventHandler(Form_KeyPress);
            this.KeyDown += new KeyEventHandler(Form_KeyDown);
            this._dlgResult = DialogResult.Cancel;
            this.FormClosing += new FormClosingEventHandler(Form_FormClosing);
            this.Enter += new EventHandler(Form_Enter);
            this.Activated += new EventHandler(Form_Activated);
            this.Load += new EventHandler(FormBase_Load);

            _isLoading = true;
            _saving = false;
            _currentPage = 0;
            _itemCount = 0;
            _totalPage = 0;
            _orderBy = "";
            _orderDirection = "";
            _keyWord = "";
            _dicExchaneValue = null;
            _dicRootValue = null;

            */


        }

        private TabOrderManager tom;//= new TabOrderManager();
        private void Init_TabOrder()
        {
            tom = new TabOrderManager(this);
            tom.SetTabOrder(TabScheme.AcrossFirst);
        }

        public FormBase()
        {
            InitializeComponent();

            //Đặt lại Icon của form cho tất cả các form
            if (this.ShowIcon)
                this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
        }

        #endregion

        private Dictionary<string, MethodInvoker> _dicTimerCallback;

        private Dictionary<string, Timer> _dicTimerControl;

        public string Timer_Invoke(TimeSpan timeInterval, MethodInvoker callbackInvoke)
        {
            return Timer_Invoke(timeInterval, callbackInvoke, true);
        }

        private string Timer_Invoke(TimeSpan timeInterval, MethodInvoker callbackInvoke, bool limitTimer)
        {
            if (limitTimer && timeInterval.TotalSeconds < 10)
            {
                throw new ArgumentException("Interval must greater than or equal 10 seconds", "timeInterval");
            }
            if (_dicTimerCallback == null)
            {
                _dicTimerCallback = new Dictionary<string, MethodInvoker>();
                _dicTimerControl = new Dictionary<string, Timer>();
            }
            Timer timer = new Timer();
            timer.Tag = Guid.NewGuid().ToString();
            //
            _dicTimerCallback.Add(timer.Tag.ToString(), callbackInvoke);
            _dicTimerControl.Add(timer.Tag.ToString(), timer);
            //
            timer.Interval = Convert.ToInt32(timeInterval.TotalMilliseconds);
            timer.Tick += Timer_Tick;
            timer.Start();
            //
            return timer.Tag.ToString();
        }

        public void Timer_Revoke(string timerID)
        {
            if ((_dicTimerCallback != null) && _dicTimerCallback.ContainsKey(timerID))
            {
                _dicTimerCallback.Remove(timerID);
                _dicTimerControl[timerID].Stop();
                _dicTimerControl[timerID].Dispose();
                _dicTimerControl.Remove(timerID);
            }
            else
            {
                throw new Exception("Timer ID '" + timerID + "' not found in list");
            }
        }

        private void Timer_RevokeAll()
        {
            if (_dicTimerCallback == null)
                return;
            foreach (string timerID in _dicTimerCallback.Keys)
            {
                _dicTimerControl[timerID].Stop();
                _dicTimerControl[timerID].Dispose();
            }
            _dicTimerCallback.Clear();
            _dicTimerControl.Clear();
        }

        //Store in queue timer when form inactive
        private List<string> m_lstTimer = new List<string>();
        private void Timer_Tick(object sender, EventArgs e)
        {
            string sKey = ((Timer)sender).Tag.ToString();
            if (_dicTimerCallback.ContainsKey(sKey))
            {
                //
                if (m_lstTimer.Contains(sKey))
                {
                    return;
                }
                else
                {
                    m_lstTimer.Add(sKey);
                }
                if (!this.IsActivated)
                    return;
                //
                try
                {
                    _dicTimerCallback[sKey].Invoke();
                }
                catch
                {
                    throw;
                }
                finally
                {
                    m_lstTimer.Remove(sKey);
                }
            }
            else
            {
                ((Timer)sender).Stop();
                ((Timer)sender).Dispose();
            }
        }

        public void Control_TabOrder(Control ctl, TabScheme tabScheme)
        {
            tom.SetSchemeForControl(ctl, tabScheme);
        }

        protected void Form_Exit(object sender, EventArgs e)
        {
            this.Close();
        }

        #region "Override function"

        public virtual void Show_Form()
        {
            //Must Override for auto show form when click menu
        }

        public virtual DialogResult Show_Form(object input)
        {
            //Must Override for auto show form when call from another
            return base.ShowDialog();
        }

        protected virtual void Init_Control()
        {
            //Must Override for init control
        }

        protected virtual void Recall_Form()
        {
            //Must Override for reload data when recall form
        }

        protected virtual void Control_Validated(object sender, System.EventArgs e)
        {
            //Must Override for handle custom control valid
        }

        protected virtual void PageIndex_Changed(Int32 newIndex)
        {
            //Must Override for handle page control page index change
        }

        protected virtual void PageSize_Changed(Int32 newSize)
        {
            //Must Override for handle page control page size change
        }

        #endregion

        //public void InitDialog()
        //{
        //    FormGlobals.Form_InitDialog(this);
        //    m_initDialog = true;
        //    FormGlobals.App_ProgressShow(new MethodInvoker(Init_Form));
        //}
        //public void InitSingle()
        //{
        //    m_initDialog = false;
        //    FormGlobals.App_ProgressShow(new MethodInvoker(Init_Form));
        //    Init_Form();
        //}

        public new DialogResult ShowDialog()
        {
            FormGlobals.Form_InitDialog(this);
            //
            m_initDialog = true;
            FormGlobals.App_ProgressShow(new MethodInvoker(Init_Form));
            //Splash.Show(new MethodInvoker(Init_Form));
            //
            return base.ShowDialog();
        }

        protected new void Show()
        {
            Show(WeifenLuo.WinFormsUI.Docking.DockState.Document);
        }

        protected void Show(WeifenLuo.WinFormsUI.Docking.DockState docState)
        {
            FormBase f = FormGlobals.Form_FindInTab(this);
            if (f == null)
            {
                m_initDialog = false;
                FormGlobals.App_ProgressShow(new MethodInvoker(Init_Form));
                //Splash.Show(new MethodInvoker(Init_Form));
            }
            else
            {
                if (f.MenuName == this.MenuName)
                {
                    f.InitValue = this.InitValue;
                    f.InputValue = this.InputValue;
                    f.Recall_Form();
                }
                else
                {
                    throw new Exception("This form already init in menu '" + f.MenuName + "' with same title");
                }
            }
            _IsLoading = false;
            if (f == null)
            {
                this.Show(FormGlobals.dockPanel, docState);
                FormGlobals.dockPanel.BringToFront();
            }
            else
            {
                f.Activate();
                this.Close();
            }
        }

        private bool m_IsActived;
        private Control firstFocusControl;
        /// <summary>
        /// Control đầu tiên sẽ được focus đến khi mở form
        /// Sau khi sự kiện FormBase_Activated
        /// </summary>
        public Control FirstFocusControl
        {
            get { return firstFocusControl; }
            set { firstFocusControl = value; }
        }

        private void FormBase_Activated(object sender, System.EventArgs e)
        {
            if (!m_IsActived)
            {
                m_IsActived = true;

                //Nếu đặt control focus đầu tiên, thì focus đến
                //Không thì mặc định focus đến control có thứ tự đầu tiên của form

                if (!IsLoading && firstFocusControl != null)
                {
                    firstFocusControl.Focus();
                }
                else
                {
                    FormGlobals.Control_FirstFocus(this);
                }
            }
            else
            {
                string sKey = null;
                while (m_lstTimer.Count > 0)
                {
                    sKey = m_lstTimer[0];
                    try
                    {
                        _dicTimerCallback[sKey].Invoke();
                    }
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        m_lstTimer.Remove(sKey);
                    }
                }

            }
        }

        protected new void Closed()
        {
            if ((_dicTimerCallback != null))
                _dicTimerCallback.Clear();
        }

        protected void Control_HandlerValid(params Control[] arrParent)
        {
            foreach (Control ctlParent in arrParent)
            {
                Control_HandlerValid(ctlParent);
            }
        }

        protected void Control_HandlerValid(Control ctlParent)
        {
            foreach (Control ctlChild in ctlParent.Controls)
            {
                if (ctlChild is TextBox || ctlChild is CheckBox || ctlChild is RadioButton || ctlChild is RadioButtonList)
                {
                    ctlChild.Validated += Control_Validating;
                }
                else if (ctlChild.HasChildren)
                {
                    Control_HandlerValid(ctlChild);
                }
            }
        }

        private void Control_Validating(object sender, System.EventArgs e)
        {
            Control ctlChild = sender as Control;
            FormGlobals.FormControlExt formExt = FormGlobals.Control_GetExtension(ctlChild);
            if (FormGlobals.Control_GetValue(ctlChild) == formExt.PrevValue)
                return;
            Control_Validated(sender, e);
            formExt.PrevValue = FormGlobals.Control_GetValue(ctlChild);
            FormGlobals.Control_SetExtension(ctlChild, formExt);
        }



        //Đặt phân quyền tự động cho các nút Button
        public void Control_EnableByRole(Control parent)
        {
            Control_EnableByRole(parent, 1);
        }

        public void Control_EnableByRole(Control parent, int rows)
        {
            if (_listRole == null) return;
            if (parent is ToolStrip)
            {
                foreach (ToolStripItem ctlChild in ((ToolStrip)parent).Items)
                {
                    if (ctlChild is ToolStripButton)
                    {
                        if (ctlChild.Visible)
                        {
                            if (ctlChild.Name.Substring(3).IndexOf("New") >= 0
                                || ctlChild.Name.Substring(3).IndexOf("Add") >= 0)
                                ctlChild.Enabled = _listRole.CreateRight;

                            if (ctlChild.Name.Substring(3).IndexOf("View") >= 0
                                || ctlChild.Name.Substring(3).IndexOf("Edit") >= 0)
                            {
                                ctlChild.Enabled = (_listRole.ViewRight || _listRole.UpdateRight);
                                if (rows == 0)
                                    ctlChild.Enabled = false;
                            }

                            if (ctlChild.Name.Substring(3).IndexOf("Save") >= 0
                                || ctlChild.Name.Substring(3).IndexOf("Update") >= 0)
                            {
                                ctlChild.Enabled = _listRole.UpdateRight;
                                if (rows == 0)
                                    ctlChild.Enabled = false;
                            }

                            if (ctlChild.Name.Substring(3).IndexOf("Del") >= 0
                                || ctlChild.Name.Substring(3).IndexOf("Delete") >= 0)
                            {
                                ctlChild.Enabled = _listRole.DeleteRight;
                                if (rows == 0)
                                    ctlChild.Enabled = false;
                            }
                            if (ctlChild.Name.Substring(3).IndexOf("Print") >= 0
                                || ctlChild.Name.Substring(3).IndexOf("Export") >= 0
                                || ctlChild.Name.Substring(3).IndexOf("Excel") >= 0
                                || ctlChild.Name.Substring(3).IndexOf("Preview") >= 0)
                            {
                                ctlChild.Enabled = _listRole.PrintRight;
                                if (rows == 0)
                                    ctlChild.Enabled = false;
                            }
                        }
                    }
                }
            }
            if (parent is Button)
            {
                if (parent.Visible)
                {
                    if (parent.Name.Substring(3).IndexOf("New") >= 0
                        || parent.Name.Substring(3).IndexOf("Add") >= 0)
                        parent.Enabled = _listRole.CreateRight;


                    if (parent.Name.Substring(3).IndexOf("View") >= 0
                                       || parent.Name.Substring(3).IndexOf("Edit") >= 0)
                    {
                        parent.Enabled = (_listRole.ViewRight || _listRole.UpdateRight);
                        if (rows == 0)
                            parent.Enabled = false;
                    }

                    if (parent.Name.Substring(3).IndexOf("Save") >= 0
                        || parent.Name.Substring(3).IndexOf("Update") >= 0)
                    {
                        parent.Enabled = _listRole.UpdateRight;
                        if (rows == 0)
                            parent.Enabled = false;
                    }


                    if (parent.Name.Substring(3).IndexOf("Del") >= 0
                                || parent.Name.Substring(3).IndexOf("Delete") >= 0)
                    {
                        parent.Enabled = _listRole.DeleteRight;
                        if (rows == 0)
                            parent.Enabled = false;
                    }
                    if (parent.Name.Substring(3).IndexOf("Print") >= 0
                        || parent.Name.Substring(3).IndexOf("Export") >= 0
                        || parent.Name.Substring(3).IndexOf("Excel") >= 0
                        || parent.Name.Substring(3).IndexOf("Preview") >= 0)
                    {
                        parent.Enabled = _listRole.PrintRight;
                        if (rows == 0)
                            parent.Enabled = false;
                    }
                }
            }



            foreach (Control i in parent.Controls)
                Control_EnableByRole(i, rows);

        }

        //Đặt image tự động cho các nút Button
        public void Button_InitCommand()
        {
            Control pnlCommand = (Control)FormGlobals.Find_Control<Control>(this, "pnlCommand");
            if ((pnlCommand != null))
            {
                FormGlobals.Panel_InitCommand(pnlCommand);


                string[] arrButton = new string[] { "Cancel", "Close", "Exit" };
                foreach (Control ctl in pnlCommand.Controls)
                {
                    if (ctl is Button)
                    {
                        //Set auto close
                        if (Array.IndexOf(arrButton, ctl.Name.Substring(3)) >= 0)
                        {
                            btnExit = (Button)ctl;
                            ctl.Click += Form_Exit;
                            btnExit.CausesValidation = false;
                        }
                        //
                        HotKey_Init(ctl);
                    }
                }
                //Init Button Permission
                //if (!string.IsNullOrEmpty(this.UserName))
                //{
                //    DataTable m_dtButton = App_Functions_Controller.Instance().ListButton(this.Name);
                //    m_lstButtonPermission = Control_SetPermission(pnlCommand, m_dtButton);
                //}
            }

        }

        //Đặt image tự động cho các nút Button
        public void Button_InitCommand(Control parent)
        {
            if (parent is Button)
            {
                FormGlobals.Button_SetImage(parent);

                string[] arrButton = new string[] { "Cancel", "Close", "Exit" };
                //Set auto close
                if (Array.IndexOf(arrButton, parent.Name.Substring(3)) >= 0)
                {
                    btnExit = (Button)parent;
                    parent.Click += Form_Exit;
                    btnExit.CausesValidation = false;
                }

            }
            foreach (Control i in parent.Controls)
                Button_InitCommand(i);


        }

        //Đặt image tự động cho các nút toolbar
        public void Toolbar_InitCommand(Control parent)
        {
            if (parent is StatusStrip)
            {
                StatusStrip c = (StatusStrip)parent;
                c.RenderMode = ToolStripRenderMode.Professional;
                c.AutoSize = false;
                c.GripStyle = ToolStripGripStyle.Hidden;
                c.SizingGrip = false;
                //c.TabStop = false;
            }
            else if (parent is MenuStrip)
            {
                MenuStrip c = (MenuStrip)parent;
                c.RenderMode = ToolStripRenderMode.ManagerRenderMode;
                c.AutoSize = false;
                c.GripStyle = ToolStripGripStyle.Hidden;
                //c.TabStop = false;
            }

            else if (parent is ToolStrip)
            {
                ToolStrip c = (ToolStrip)parent;
                c.RenderMode = ToolStripRenderMode.ManagerRenderMode;
                c.AutoSize = false;
                c.GripStyle = ToolStripGripStyle.Hidden;
                //c.TabStop = false;

                string[] arrButton = new string[] { "Cancel", "Close", "Exit" };
                foreach (ToolStripItem ctlChild in ((ToolStrip)parent).Items)
                {
                    if (ctlChild is ToolStripButton)
                    {
                        //Set auto close
                        if (Array.IndexOf(arrButton, ctlChild.Name.Substring(3)) >= 0)
                        {
                            btnExitToolbar = (ToolStripButton)ctlChild;
                            ctlChild.Click += Form_Exit;
                            //btnExitToolbar.CausesValidation = false;
                        }
                        //
                        HotKey_Init(ctlChild);
                        FormGlobals.Toolbar_SetImage((ToolStripButton)ctlChild);

                        ToolStripButton button = (ToolStripButton)ctlChild;
                        if (button.Image != null)
                        {
                            if (button.Image.Size.Height < 24)
                                button.ImageScaling = ToolStripItemImageScaling.None;
                            else
                                button.ImageScaling = ToolStripItemImageScaling.SizeToFit;
                        }
                    }
                }
            }
            foreach (Control i in parent.Controls)
                Toolbar_InitCommand(i);


            ToolStrip tsToolbar = (ToolStrip)FormGlobals.Find_Control<ToolStrip>(this, "tsToolbar");
            if ((tsToolbar != null))
            {
                foreach (ToolStripItem ctlChild in tsToolbar.Items)
                {
                    if (ctlChild is ToolStripButton)
                    {
                        HotKey_Init(ctlChild);
                        FormGlobals.Toolbar_SetImage((ToolStripButton)ctlChild);
                    }
                }
            }

        }



        public void ToolStrip_SetAutoNumber(object ctrl)
        {
            //Đánh số thứ tự cho các control con trên ToolStrip

            if (ctrl is ToolStrip)
            {
                ToolStrip ms = (ToolStrip)ctrl;
                {
                    for (int i = 0; i < ms.Items.Count; i++)
                    {
                        //ms.Items[i].Text = "&" + GetMenuIndexChar(i) + ". " + ms.Items[i].Text;
                        ToolStrip_SetAutoNumber(ms.Items[i]);
                    }
                }
            }
            else if (ctrl is ToolStripTextBox)
                return;
            else if (ctrl is ToolStripDropDownButton)
            {
                ToolStripDropDownButton tsi = (ToolStripDropDownButton)ctrl;
                {
                    int numofseperator = 0;
                    for (int i = 0; i < tsi.DropDownItems.Count; i++)
                    {
                        if (tsi.DropDownItems[i] is ToolStripSeparator || !tsi.DropDownItems[i].Enabled)
                        {
                            numofseperator++;
                            continue;
                        }
                        tsi.DropDownItems[i].Text = GetStringOfIndexChar(i - numofseperator) + tsi.DropDownItems[i].Text;
                        ToolStrip_SetAutoNumber(tsi.DropDownItems[i]);
                    }
                }
            }
        }


        string GetStringOfIndexChar(int i)
        {
            string s = "&";
            if (i < 9)
                s += (i + 1).ToString();
            else
                s += Convert.ToChar((i - 9) + Convert.ToInt32('A')).ToString();
            return s + ". ";
        }

        public void MenuStrip_SetAutoNumber(object ctrl)
        {
            //Đánh số thứ tự cho các control con trên MenuStrip
            if (ctrl is MenuStrip)
            {
                MenuStrip ms = (MenuStrip)ctrl;
                {
                    for (int i = 0; i < ms.Items.Count; i++)
                    {
                        //ms.Items[i].Text = "&" + GetMenuIndexChar(i) + ". " + ms.Items[i].Text;
                        MenuStrip_SetAutoNumber(ms.Items[i]);
                    }
                }
            }
            else if (ctrl is ToolStripTextBox)
                return;
            else if (ctrl is ToolStripMenuItem)
            {
                ToolStripMenuItem tsi = (ToolStripMenuItem)ctrl;
                {
                    int numofseperator = 0;
                    for (int i = 0; i < tsi.DropDownItems.Count; i++)
                    {
                        if (tsi.DropDownItems[i] is ToolStripSeparator)
                        {
                            numofseperator++;
                            continue;
                        }
                        tsi.DropDownItems[i].Text = GetStringOfIndexChar(i - numofseperator) + tsi.DropDownItems[i].Text;
                        MenuStrip_SetAutoNumber(tsi.DropDownItems[i]);
                    }
                }
            }
        }

        public void MenuStrip_IsEnable(object ctrl)
        {
            //Quét tất cả các menu và đặt mnu.Enable = true --> Danh cho admin

            if (ctrl is MenuStrip)
            {
                MenuStrip ms = (MenuStrip)ctrl;
                {
                    for (int i = 0; i < ms.Items.Count; i++)
                    {
                        MenuStrip_IsEnable(ms.Items[i]);
                    }
                }
            }
            else if (ctrl is ToolStripTextBox)
                return;
            else if (ctrl is ToolStripMenuItem)
            {
                ToolStripMenuItem tsi = (ToolStripMenuItem)ctrl;
                {
                    for (int i = 0; i < tsi.DropDownItems.Count; i++)
                    {
                        tsi.DropDownItems[i].Enabled = true;
                        MenuStrip_IsEnable(tsi.DropDownItems[i]);
                    }
                }
            }
        }

        public void MenuStrip_EnabledChanged(object ctrl)
        {
            //Quét tất cả các menu và đặt mnu.ShowShortcutKeys = mnu.Enable

            if (ctrl is MenuStrip)
            {
                MenuStrip ms = (MenuStrip)ctrl;
                {
                    for (int i = 0; i < ms.Items.Count; i++)
                    {
                        MenuStrip_EnabledChanged(ms.Items[i]);
                    }
                }
            }
            else if (ctrl is ToolStripTextBox)
                return;
            else if (ctrl is ToolStripMenuItem)
            {
                ToolStripMenuItem tsi = (ToolStripMenuItem)ctrl;
                {
                    for (int i = 0; i < tsi.DropDownItems.Count; i++)
                    {
                        tsi.DropDownItems[i].EnabledChanged += new EventHandler(menu_EnabledChanged);
                        MenuStrip_EnabledChanged(tsi.DropDownItems[i]);
                    }
                }
            }
        }

        void menu_EnabledChanged(object sender, EventArgs e)
        {
            ToolStripMenuItem m = (ToolStripMenuItem)sender;
            if (m.Name == "mnuExit" || m.Name == "mnuLogin")
                m.ShowShortcutKeys = true;
            else
                m.ShowShortcutKeys = m.Enabled;
        }

        public string GetUserEdit(string strUserName, DateTime CreateDate, string LastUser, DateTime LastUpdate)
        {
            string str = "";
            if (LastUser != null && LastUser.Trim().Length > 0)
                str = " Lưu cuối bởi: " + LastUser + " (" + LastUpdate.ToString("dd/MM/yyyy h:mm tt") + ");";
            if (strUserName != null && CreateDate != DateTime.MinValue)
                str = str + " Tạo bởi: " + strUserName + " (" + CreateDate.ToString("dd/MM/yyyy h:mm tt") + ")";
            return str;
        }

        public string GetUserCreate()
        {
            return "Người tạo: " + FormGlobals.strUserName + " (" + DateTime.Now.ToString("dd/MM/yyyy h:mm tt") + ")";
        }


        protected void Form_FormClosing(object sender, FormClosingEventArgs e)
        {
            bool hasChanged = Form_HasChanged(this, _dicRootValue);

            object obj = (object)Control_GetByName(this, "btnSave");
            if (obj != null)
            {
                if (obj.GetType().Name == "ToolStripButton")
                {
                    ToolStripButton tsSave = ((ToolStripButton)obj);
                    if (tsSave.Visible && tsSave.Enabled)
                        if (hasChanged)
                        {
                            if (FormGlobals.Message_Confirm(UIMessage.DATACHANGED))
                            {
                                tsSave.PerformClick();
                                e.Cancel = hasChanged;
                            }
                        }
                }
                else if (obj.GetType().Name == "Button")
                {
                    Button btnSave = (Button)obj;

                    if (btnSave.Visible && btnSave.Enabled)
                        if (hasChanged)
                        {
                            if (FormGlobals.Message_Confirm(UIMessage.DATACHANGED))
                            {
                                btnSave.PerformClick();
                                e.Cancel = hasChanged;
                            }
                        }
                }
            }
            this.DialogResult = _dlgResult;
        }

        protected void Form_Enter(object sender, EventArgs e)
        {
            //Dùng Sự kiện Enter để Select All text in TextBox

            Control c = ((Control)sender);

            if (c is TextBox)
                (c as TextBox).SelectAll();
            else if (c is RichTextBox)
                (c as RichTextBox).SelectAll();
            else if (c is MaskedTextBox)
                (c as MaskedTextBox).SelectAll();

            foreach (Control i in c.Controls)
                Form_Enter(i, e);

        }

        protected void Form_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Escape))
            {
                if (this.Name.ToLower().Contains("frmmain") || this.Name.ToLower().Contains("frmsystem") || this.Name.ToLower().Contains("frmLogin"))
                    return;
                if (this.ParentForm != null)
                    return;
                this.Close();
                e.Handled = true;

            }
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                if (this.Name.ToLower().Contains("frmmain") || this.Name.ToLower().Contains("frmsystem"))
                    return;

                this.ProcessTabKey(true);
                e.Handled = true;

            }
        }

        protected void Form_KeyDown(object sender, KeyEventArgs e)
        {
            bool isclick = false;
            if (this.ActiveControl != null)
            {
                if (e.KeyValue == 27 && this.ActiveControl.GetType().Name == "MultiColumnComboBox")
                {
                    if (!((CustomUIControls.MultiColumnComboBox)this.ActiveControl).DroppedDown)
                    {
                        if (this.ParentForm != null)
                            return;

                        e.Handled = true;
                        this.Close();
                    }
                }
            }
            switch (e.KeyData)
            {
                case (Keys.Control | Keys.N):
                    isclick = (Control_Click("btnNew") || Control_Click("btnAdd") || Control_Click("btnAddNew"));
                    break;

                case Keys.F3:
                    isclick = (Control_Click("btnSave") || Control_Click("btnOK") || Control_Click("btnEdit") || Control_Click("btnView"));
                    break;

                case (Keys.Control | Keys.S):
                    isclick = Control_Click("btnSave");
                    break;

                case Keys.F5:
                    isclick = (Control_Click("btnPlus") || Control_Click("btnRefresh") || Control_Click("btnSearch"));
                    break;

                case (Keys.Control | Keys.Delete):
                    isclick = (Control_Click("btnDel") || Control_Click("btnDelDetail") || Control_Click("btnDelete"));
                    break;

                case Keys.PageUp:
                    isclick = Control_Click("btnPrevious");
                    break;

                case Keys.PageDown:
                    isclick = Control_Click("btnNext");
                    break;
            }
            if (isclick)
                e.Handled = true;

        }

        public bool Control_Click(string name)
        {
            // Tìm control
            //Cách 2: 
            object ctrl = (object)Control_GetByName(this, name);
            if (ctrl != null)
            {

                if (ctrl.GetType().Name == "ToolStripButton")
                {
                    if (((ToolStripButton)ctrl).Enabled && ((ToolStripButton)ctrl).Visible)
                        ((ToolStripButton)ctrl).PerformClick();
                }
                else
                {
                    if (((Button)ctrl).Enabled && ((Button)ctrl).Visible)
                        ((Button)ctrl).PerformClick();
                }
                return true;
            }
            else
                return false;
        }

        public void Control_Color(Control ctrl)
        {
            Font font = new Font("Tahoma", 8.25F, FontStyle.Regular);
            Font fontBold = new Font("Tahoma", 8.25F, FontStyle.Bold);
            Font fontItalic = new Font("Tahoma", 8.25F, FontStyle.Italic);

            Font font9 = new Font("Tahoma", 9, FontStyle.Regular);
            Font font9Bold = new Font("Tahoma", 9, FontStyle.Bold);
            Font font9Italic = new Font("Tahoma", 9, FontStyle.Italic);

            //ctrl.BackColor = _backgroundColor;

            if (ctrl is Form)
            {
                if (ctrl.BackColor == SystemColors.Control)
                    ctrl.BackColor = _backgroundColor;
            }
            if (ctrl is TabControl)
            {
                // ctrl.Font = font;
                if (ctrl.BackColor == SystemColors.Control)
                    ctrl.BackColor = _backgroundColor;
            }
            if (ctrl is TabPage)
            {
                // ctrl.Font = font;
                if (ctrl.BackColor == SystemColors.Control)
                    ctrl.BackColor = _backgroundColor;
            }
            if (ctrl is GroupBox)
            {
                // ctrl.Font = font;
                if (ctrl.BackColor == SystemColors.Control)
                    if (ctrl.BackColor == SystemColors.Control)
                        ctrl.BackColor = _backgroundColor;
            }
            if (ctrl is HeaderGroupBox)
            {
                // ctrl.Font = font9;
                if (ctrl.BackColor == SystemColors.Control)
                    ctrl.BackColor = _backgroundColor;
            }
            if (ctrl is Panel)
            {
                //ctrl.Font = font;
                if (ctrl.BackColor == SystemColors.Control)
                    ctrl.BackColor = _backgroundColor;
            }
            else if (ctrl is DataGridView)
            {
                ((DataGridView)ctrl).BackgroundColor = SystemColors.Window;//= Program.BgrColor;

                //((DataGridView)ctrl).DefaultCellStyle.Font = new Font("Arial", 9, ctrl.Font.Style);
                ((DataGridView)ctrl).ColumnHeadersDefaultCellStyle.Font = new Font("Arial", 9, FontStyle.Bold);
            }
            else if (ctrl is Label)
            {
                //ctrl.Font = font;
            }
            else if (ctrl is Button)
            {
                //ctrl.Font = new Font("Tahoma", 8.5F, FontStyle.Bold); ;
            }
            else if (ctrl is TextBox || ctrl is RichTextBox || ctrl is DateTimePicker || ctrl is MaskedTextBox)
            {
                //ctrl.Font = fontBold;
            }
            else if (ctrl is ListBox)
            {
                //ctrl.Font = font9;
            }
            else if (ctrl is TreeView)
            {
                //ctrl.Font = font;
            }
            else if (ctrl is MenuStrip)
            {
                //ctrl.Font = font;
            }
            else if (ctrl is StatusStrip)
            {
                //ctrl.Font = font;
            }
            else if (ctrl is ToolStrip)
            {
                Control c = null;

                //if (((ToolStrip)ctrl).RenderMode != ToolStripRenderMode.ManagerRenderMode)
                //    ((ToolStrip)ctrl).BackColor = _backgroundColor;

                foreach (ToolStripItem item in ((ToolStrip)ctrl).Items)
                {
                    //item.Font = font;
                    //switch (item.GetType().Name)
                    //{
                    //    case "ToolStripComboBox":
                    //        c = ((ToolStripComboBox)item).Control;

                    //        break;
                    //    case "ToolStripTextBox":
                    //        c = ((ToolStripTextBox)item).Control;
                    //        break;
                    //}
                }

            }
            else if (ctrl is CustomUIControls.MultiColumnComboBox)
            {
                //ctrl.Font = fontBold;
            }
            else if (ctrl is ComboBox)
            {
                //ctrl.Font = fontBold;
            }
            else if (ctrl is DockPanel)
            {
                ((DockPanel)ctrl).Skin.AutoHideStripSkin.TextFont = font9;
                ((DockPanel)ctrl).Skin.DockPaneStripSkin.TextFont = font9;
            }

            foreach (Control i in ctrl.Controls)
                Control_Color(i);
        }

        public void SaveFileRegistration(string content)
        {
            // Create a new SaveFileDialog object
            string fileName = "Registration";
            using (SaveFileDialog dlgSave = new SaveFileDialog())
                try
                {
                    // Available file extensions
                    //dlgSave.Filter = "All Files (*.*)|*.*";
                    dlgSave.DefaultExt = "txt";
                    dlgSave.Filter = "Text File (.txt)|*.txt";
                    dlgSave.FilterIndex = 1;
                    dlgSave.FileName = fileName;
                    // SaveFileDialog title
                    dlgSave.Title = "Save";
                    // Show SaveFileDialog
                    if (dlgSave.ShowDialog() == DialogResult.OK && dlgSave.FileName.Length > 0)
                    {
                        // Save file as utf8 without byte order mark (BOM)
                        // ref: http://msdn.microsoft.com/en-us/library/s064f8w2.aspx

                        //UTF8Encoding utf8 = new UTF8Encoding();
                        //StreamWriter sw = new StreamWriter(dlgSave.FileName, false, utf8);
                        //sw.Write(str);
                        //sw.Close();

                        //richTextBox1.SaveFile(dlgSave.FileName);

                        StreamWriter sw = File.CreateText(dlgSave.FileName);
                        sw.WriteLine(content);
                        sw.Flush();
                        sw.Close();
                    }
                }
                catch (Exception errorMsg)
                {
                    FormGlobals.Message_Error(errorMsg);
                }
        }

        public void Control_ClearText(Control ctrl)
        {
            if (ctrl is TextBox || ctrl is RichTextBox || ctrl is MaskedTextBox)
                ctrl.Text = string.Empty;
            //else if (ctrl is ComboBox || ctrl is CustomUIControls.MultiColumnComboBox)
            //    ((ComboBox)ctrl).SelectedIndex = 0;
            //else if (ctrl is CheckBox)
            //    ((CheckBox)ctrl).Checked = false;

            // Xử lý các điều kiểm một cách đệ quy.
            // Điều này cần thiết khi có một điều kiểm chứa nhiều 
            // điều kiểm khác (ví dụ, khi bạn sử dụng Panel, 
            // GroupBox, hoặc điều kiểm container nào khác).
            foreach (Control i in ctrl.Controls)
                Control_ClearText(i);
        }

        public object Control_GetByNameX(Control.ControlCollection parent, string controlName)
        {
            object c = null;
            foreach (Control ctrl in parent)
            {
                //if (ctrl.Name.Equals(controlName))
                if (ctrl.Name.Contains(controlName))
                {
                    c = ctrl;
                    return c;
                }

                if (ctrl.GetType() == typeof(ToolStrip))
                {
                    if (ctrl.GetType() == typeof(ToolStripItem))
                    {

                        foreach (ToolStripItem item in ((ToolStrip)ctrl).Items)
                        {
                            //if (item.Name.Equals(controlName))
                            if (item.Name.Contains(controlName))
                            {
                                switch (item.GetType().Name)
                                {
                                    case "ToolStripComboBox":
                                        c = ((ToolStripComboBox)item).Control;
                                        break;
                                    case "ToolStripTextBox":
                                        c = ((ToolStripTextBox)item).Control;
                                        break;
                                    case "ToolStripDropDownButton":
                                        ToolStripDropDownButton tsi = (ToolStripDropDownButton)item;

                                        for (int i = 0; i < tsi.DropDownItems.Count; i++)
                                        {
                                            //if (item.Name.Equals(controlName))
                                            if (tsi.DropDownItems[i].Name.Contains(controlName))
                                            {
                                                c = (ToolStripMenuItem)tsi.DropDownItems[i];
                                            }
                                        }

                                        break;
                                    default:
                                        c = item;
                                        break;
                                }
                                if (c != null)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    else
                        if (ctrl.GetType() == typeof(ToolStripMenuItem))
                        {
                        }




                }

                if (ctrl.GetType() == typeof(ToolStripDropDownButton))
                {

                }
                if (c == null)
                    c = Control_GetByNameX(ctrl.Controls, controlName);
                else
                    break;
            }
            return c;
        }

        bool IsObjectHasName(object o, string name)
        {
            object n = Globals.GetPreperty(o, "Name");
            if (n is string && (string)n == name)
            {
                return true;
            }
            return false;
        }

        public object Control_GetByName(object parent, string controlName)
        {
            if (IsObjectHasName(parent, controlName))
                return parent;
            object ret = null;
            if (parent is ToolStripDropDownItem)
            {
                ToolStripDropDownItem ddi = (ToolStripDropDownItem)parent;
                foreach (ToolStripItem sddi in ddi.DropDownItems)
                {
                    ret = Control_GetByName(sddi, controlName);
                    if (ret != null)
                        return ret;
                }
            }
            else if (parent is ToolStripMenuItem)
            {
                ToolStripMenuItem tsi = (ToolStripMenuItem)parent;
                foreach (ToolStripItem stsi in tsi.DropDownItems)
                {
                    ret = Control_GetByName(stsi, controlName);
                    if (ret != null)
                        return ret;
                }
            }
            else if (parent is MenuItem)
            {
                MenuItem m = (MenuItem)parent;
                foreach (MenuItem mni in m.MenuItems)
                {
                    ret = Control_GetByName(mni, controlName);
                    if (ret != null)
                        return ret;
                }
            }
            else if (parent is ContextMenu)
            {
                ContextMenu c = (ContextMenu)parent;
                foreach (MenuItem mni in c.MenuItems)
                {
                    ret = Control_GetByName(mni, controlName);
                    if (ret != null)
                        return ret;
                }
            }
            else if (parent is ContextMenuStrip)
            {
                ContextMenuStrip c = (ContextMenuStrip)parent;
                foreach (ToolStripItem tsi in c.Items)
                {
                    ret = Control_GetByName(tsi, controlName);
                    if (ret != null)
                        return ret;
                }
            }
            else if (parent is ToolStrip)
            {
                ToolStrip t = (ToolStrip)parent;
                foreach (ToolStripItem tsi in t.Items)
                {
                    ret = Control_GetByName(tsi, controlName);
                    if (ret != null)
                        return ret;
                }
            }
            else if (parent is Control)
            {
                Control c = (Control)parent;
                foreach (Control sc in c.Controls)
                {
                    ret = Control_GetByName(sc, controlName);
                    if (ret != null)
                        return ret;
                }
            }
            //Tim ContextMenuStrip
            object contextMenuStrip = FormGlobals.GetPreperty(parent, "ContextMenuStrip");
            if (contextMenuStrip != null)
            {
                ret = Control_GetByName(contextMenuStrip, controlName);
                if (ret != null)
                    return ret;
            }
            //Tim ContextMenu
            object contextMenu = FormGlobals.GetPreperty(parent, "ContextMenu");
            if (contextMenu != null)
            {
                ret = Control_GetByName(contextMenu, controlName);
                if (ret != null)
                    return ret;
            }
            return null;
        }

        public void PageIndex(ToolStripLabel _ctrlPageIndex, ToolStripLabel _ctrlTotalRows)
        {

            _totalPage = _itemCount % _pageSize > 0 ? (_itemCount / _pageSize) + 1 : (_itemCount / _pageSize);
            if (_totalPage == 0)
            {
                _ctrlPageIndex.Text = "0" + "/" + _totalPage.ToString();
                if (_ctrlTotalRows != null)
                    _ctrlTotalRows.Text = "  Không có dòng nào!  ";
            }
            else
            {
                _ctrlPageIndex.Text = (_currentPage + 1).ToString() + "/" + _totalPage.ToString();
                if (_ctrlTotalRows != null)
                    _ctrlTotalRows.Text = " Có " + _itemCount.ToString("#,#0") + " dòng ";
            }
        }

        public void PageIndex(Control _ctrlPageIndex, Control _ctrlTotalRows)
        {
            _totalPage = _itemCount % _pageSize > 0 ? (_itemCount / _pageSize) + 1 : (_itemCount / _pageSize);
            if (_totalPage == 0)
            {
                _ctrlPageIndex.Text = "0" + "/" + _totalPage.ToString();
                if (_ctrlTotalRows != null)
                    _ctrlTotalRows.Text = "  Không có dòng nào!  ";
            }
            else
            {
                _ctrlPageIndex.Text = (_currentPage + 1).ToString() + "/" + _totalPage.ToString();
                if (_ctrlTotalRows != null)
                    _ctrlTotalRows.Text = " Có " + _itemCount.ToString("#,#0") + " dòng ";
            }
        }

        public void Role2Control(tbl_RoleRight_Info listRight, object key)
        {
            ToolStripButton tsNew = new ToolStripButton();
            ToolStripButton tsSave = new ToolStripButton();
            ToolStripButton tsEdit = new ToolStripButton();
            ToolStripButton tsDel = new ToolStripButton();
            ToolStripButton tsView = new ToolStripButton();
            ToolStripButton tsPrint = new ToolStripButton();
            ToolStripButton tsExcel = new ToolStripButton();

            Button btnNew = new Button();
            Button btnSave = new Button();
            Button btnEdit = new Button();
            Button btnDel = new Button();
            Button btnView = new Button();
            Button btnPrint = new Button();
            Button btnExcel = new Button();

            ToolStripMenuItem mnuNew = new ToolStripMenuItem();
            ToolStripMenuItem mnuSave = new ToolStripMenuItem();
            ToolStripMenuItem mnuEdit = new ToolStripMenuItem();
            ToolStripMenuItem mnuDel = new ToolStripMenuItem();
            ToolStripMenuItem mnuView = new ToolStripMenuItem();
            ToolStripMenuItem mnuPrint = new ToolStripMenuItem();
            ToolStripMenuItem mnuExcel = new ToolStripMenuItem();

            object ctrlNew = (object)Control_GetByName(this, "btnNew");
            if (ctrlNew == null)
                ctrlNew = (object)Control_GetByName(this, "btnAdd");

            object ctrlSave = (object)Control_GetByName(this, "btnSave");
            object ctrlEdit = (object)Control_GetByName(this, "btnEdit");
            object ctrlDel = (object)Control_GetByName(this, "btnDel");
            object ctrlView = (object)Control_GetByName(this, "btnView");

            object ctrlPrint = (object)Control_GetByName(this, "btnPrint");
            if (ctrlPrint == null)
                ctrlPrint = (object)Control_GetByName(this, "btnPreview");

            object ctrlExcel = (object)Control_GetByName(this, "btnExcel");
            if (ctrlExcel == null)
                ctrlExcel = (object)Control_GetByName(this, "btnExport");


            object tsmiNew = (object)Control_GetByName(this, "mnuNew");
            if (tsmiNew == null)
                tsmiNew = (object)Control_GetByName(this, "mnuAdd");

            object tsmiSave = (object)Control_GetByName(this, "mnuSave");

            object tsmiEdit = (object)Control_GetByName(this, "mnuEdit");

            object tsmiDel = (object)Control_GetByName(this, "mnuDel");
            if (tsmiDel == null)
                tsmiDel = (object)Control_GetByName(this, "mnuDelete");

            object tsmiView = (object)Control_GetByName(this, "mnuView");

            object tsmiPrint = (object)Control_GetByName(this, "mnuPrint");
            if (tsmiPrint == null)
                tsmiPrint = (object)Control_GetByName(this, "mnuPreview");

            object tsmiExcel = (object)Control_GetByName(this, "mnuExcel");
            if (tsmiExcel == null)
                tsmiExcel = (object)Control_GetByName(this, "mnuExport");


            Microsoft.Reporting.WinForms.ReportViewer rpt = (Microsoft.Reporting.WinForms.ReportViewer)Control_GetByName(this, "reportViewer1");

            //Tìm control and set role for //ToolStripButton or Button
            if (ctrlNew != null)
            {
                if (ctrlNew.GetType().Name == "ToolStripButton")
                    tsNew = ((ToolStripButton)ctrlNew);
                else if (ctrlNew.GetType().Name == "ToolStripMenuItem")
                    mnuNew = ((ToolStripMenuItem)ctrlNew);
                else
                    btnNew = ((Button)ctrlNew);
            }
            if (ctrlSave != null)
            {
                if (ctrlSave.GetType().Name == "ToolStripButton")
                    tsSave = ((ToolStripButton)ctrlSave);
                else if (ctrlSave.GetType().Name == "ToolStripMenuItem")
                    mnuSave = ((ToolStripMenuItem)ctrlSave);
                else
                    btnSave = ((Button)ctrlSave);
            }
            if (ctrlEdit != null)
            {
                if (ctrlEdit.GetType().Name == "ToolStripButton")
                    tsEdit = ((ToolStripButton)ctrlEdit);
                else if (ctrlEdit.GetType().Name == "ToolStripMenuItem")
                    mnuEdit = ((ToolStripMenuItem)ctrlEdit);
                else
                    btnEdit = ((Button)ctrlEdit);
            }
            if (ctrlDel != null)
            {
                if (ctrlDel.GetType().Name == "ToolStripButton")
                    tsDel = ((ToolStripButton)ctrlDel);
                else if (ctrlDel.GetType().Name == "ToolStripMenuItem")
                    mnuDel = ((ToolStripMenuItem)ctrlDel);
                else
                    btnDel = ((Button)ctrlDel);
            }
            if (ctrlView != null)
            {
                if (ctrlView.GetType().Name == "ToolStripButton")
                    tsView = ((ToolStripButton)ctrlView);
                else if (ctrlView.GetType().Name == "ToolStripMenuItem")
                    mnuView = ((ToolStripMenuItem)ctrlView);
                else
                    btnView = ((Button)ctrlView);
            }
            if (ctrlPrint != null)
            {
                if (ctrlPrint.GetType().Name == "ToolStripButton")
                    tsPrint = ((ToolStripButton)ctrlPrint);
                else if (ctrlPrint.GetType().Name == "ToolStripMenuItem")
                    mnuPrint = ((ToolStripMenuItem)ctrlPrint);
                else
                    btnPrint = ((Button)ctrlPrint);
            }
            if (ctrlExcel != null)
            {
                if (ctrlExcel.GetType().Name == "ToolStripButton")
                    tsExcel = ((ToolStripButton)ctrlExcel);
                else if (ctrlExcel.GetType().Name == "ToolStripMenuItem")
                    mnuExcel = ((ToolStripMenuItem)ctrlExcel);
                else
                    btnExcel = ((Button)ctrlExcel);
            }

            //Tìm control and set role for contextMenuStrip
            if (tsmiNew != null)
            {
                if (tsmiNew.GetType().Name == "ToolStripMenuItem")
                    mnuNew = ((ToolStripMenuItem)tsmiNew);
            }
            if (tsmiSave != null)
            {
                if (tsmiSave.GetType().Name == "ToolStripMenuItem")
                    mnuSave = ((ToolStripMenuItem)tsmiSave);
            }
            if (tsmiEdit != null)
            {
                if (tsmiEdit.GetType().Name == "ToolStripMenuItem")
                    mnuEdit = ((ToolStripMenuItem)tsmiEdit);
            }
            if (tsmiDel != null)
            {
                if (tsmiDel.GetType().Name == "ToolStripMenuItem")
                    mnuDel = ((ToolStripMenuItem)tsmiDel);
            }
            if (tsmiView != null)
            {
                if (tsmiView.GetType().Name == "ToolStripMenuItem")
                    mnuView = ((ToolStripMenuItem)tsmiView);
            }
            if (tsmiPrint != null)
            {
                if (tsmiPrint.GetType().Name == "ToolStripMenuItem")
                    mnuPrint = ((ToolStripMenuItem)tsmiPrint);
            }
            if (tsmiExcel != null)
            {
                if (tsmiExcel.GetType().Name == "ToolStripMenuItem")
                    mnuExcel = ((ToolStripMenuItem)tsmiExcel);
            }




            //Phân quyền control
            if (_listRole != null)
            {
                tsNew.Enabled = btnNew.Enabled = mnuNew.Enabled = _listRole.CreateRight;
                if (tsDel.Visible)
                    tsDel.Enabled = _listRole.DeleteRight;

                if (btnDel.Visible)
                    btnDel.Enabled = _listRole.DeleteRight;

                if (mnuDel.Visible)
                    mnuDel.Enabled = _listRole.DeleteRight;

                tsEdit.Enabled = btnEdit.Enabled = mnuEdit.Enabled = (_listRole.UpdateRight || _listRole.ViewRight);
                tsView.Enabled = btnView.Enabled = mnuView.Enabled = _listRole.ViewRight;
                tsPrint.Enabled = btnPrint.Enabled = tsExcel.Enabled = btnExcel.Enabled = mnuExcel.Enabled = _listRole.PrintRight;
                if (rpt != null)
                    rpt.ShowExportButton = rpt.ShowPrintButton = _listRole.PrintRight;

                if (key != null)
                {
                    if (key is String)
                    {
                        if (btnNew.Enabled && Globals.ToString(key) == "")
                        {
                            tsSave.Enabled = btnSave.Enabled = _listRole.CreateRight;
                        }
                        else
                        {
                            tsSave.Enabled = btnSave.Enabled = _listRole.UpdateRight;
                        }
                    }
                    else if (key is int)
                    {
                        if (btnNew.Enabled && Globals.ToInt32(key) == 0)
                            tsSave.Enabled = btnSave.Enabled = _listRole.CreateRight;
                        else
                            tsSave.Enabled = btnSave.Enabled = _listRole.UpdateRight;
                    }
                }
                else
                {
                    tsSave.Enabled = btnSave.Enabled = _listRole.UpdateRight;
                }

            }
            else
            {
                tsNew.Enabled = false;
                tsSave.Enabled = false;
                tsEdit.Enabled = false;
                tsDel.Enabled = false;
                tsView.Enabled = false;
                tsPrint.Enabled = false;
                tsExcel.Enabled = false;

                btnNew.Enabled = false;
                btnSave.Enabled = false;
                btnEdit.Enabled = false;
                btnDel.Enabled = false;
                btnView.Enabled = false;
                btnPrint.Enabled = false;
                btnExcel.Enabled = false;

                mnuNew.Enabled = false;
                mnuSave.Enabled = false;
                mnuEdit.Enabled = false;
                mnuDel.Enabled = false;
                mnuView.Enabled = false;
                mnuPrint.Enabled = false;
                mnuExcel.Enabled = false;

                if (rpt != null)
                    rpt.ShowExportButton = rpt.ShowPrintButton = false;
            }
        }



        #region ========= Find Control Chagne Value ===============================================

        public Dictionary<String, String> Control_GetValue(Control parentControl)
        {
            Dictionary<String, String> retVal = new Dictionary<String, String>();
            foreach (Control ctl in parentControl.Controls)
            {
                if (!(ctl is DataGridView) && ctl.HasChildren)
                {
                    Dictionary<String, String> tmp = Control_GetValue(ctl);
                    foreach (String key in tmp.Keys)
                        //if (retVal.ContainsKey(key))
                        //{
                        //    retVal.Remove(key);
                        //retVal.Add(key, tmp[key]);
                        //}
                        if (!retVal.ContainsKey(key))
                            retVal.Add(key, tmp[key]);

                }
                else
                    Control_SaveValue(ctl, retVal);
            }
            return retVal;
        }

        public void Control_SaveValue(Control c, Dictionary<String, String> initValue)
        {
            if (initValue == null) return;
            String val = Control_Value(c);
            //if (String.IsNullOrEmpty(val)) return;
            if (initValue.ContainsKey(c.Name))
                initValue[c.Name] = val;
            else
                initValue.Add(c.Name, val);
        }

        public bool Form_HasChanged(Control c, Dictionary<String, String> initRootValue)
        {
            if (Control_HasChanged(c, initRootValue))
            {
                return true;
            }
            foreach (Control sc in c.Controls)
            {
                if (Form_HasChanged(sc, initRootValue))
                    return true;
            }
            return false;
        }

        public bool Control_HasChanged(Control c, Dictionary<String, String> initValue)
        {
            bool retVal = false;

            if (initValue != null)
            {
                String val = Control_Value(c);
                if ((initValue.ContainsKey(c.Name) && initValue[c.Name] != val))
                    retVal = true;
            }
            return retVal;
        }

        private String Control_Value(Control ctl)
        {
            String val = "";
            if (ctl is TextBox)
                val = (ctl as TextBox).Text;
            else if (ctl is ComboBox)
                val = (ctl as ComboBox).SelectedIndex.ToString();
            return val;
        }

        public List<Control> Control_GetChange(Control parentControl, Dictionary<String, String> initValue)
        {
            List<Control> retVal = new List<Control>();
            foreach (Control ctl in parentControl.Controls)
            {
                String val = Control_Value(ctl);
                if (initValue != null)
                    if (initValue.ContainsKey(ctl.Name) && initValue[ctl.Name] != val)
                        retVal.Add(ctl);
            }
            return retVal;
        }

        #endregion =================================================================================

        System.Windows.Forms.SortOrder _SortDirection = System.Windows.Forms.SortOrder.None;
        public void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e, MethodInvoker ShowLoadData)
        {
            DataGridView dgvList = (DataGridView)sender;
            if (dgvList.RowCount <= 0) return; if (dgvList.Columns[e.ColumnIndex].SortMode == DataGridViewColumnSortMode.Programmatic)
            {
                if (_orderBy != dgvList.Columns[e.ColumnIndex].Name)
                {
                    if (!string.IsNullOrEmpty(_orderBy) && dgvList.Columns.Contains(_orderBy))
                        dgvList.Columns[_orderBy].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.None;
                    _orderBy = dgvList.Columns[e.ColumnIndex].Name;
                    _SortDirection = System.Windows.Forms.SortOrder.Ascending;
                }
                else
                {
                    if (_SortDirection == System.Windows.Forms.SortOrder.None)
                        _SortDirection = System.Windows.Forms.SortOrder.Ascending;
                    else
                        _SortDirection = 3 - _SortDirection;
                }

                if (_SortDirection == System.Windows.Forms.SortOrder.Ascending || _SortDirection == System.Windows.Forms.SortOrder.None)
                    _orderDirection = "ASC";
                else
                    _orderDirection = "DESC";

                //
                ShowLoadData();
                //
                dgvList.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = _SortDirection;
            }
        }


    }

}
